package com.gitee.loyo.controller;

import com.gitee.loyo.Application;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import javax.ws.rs.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AssertsController {

    @GET
    @Path("/asserts/*")
    public void readAsserts(HttpServerRequest request, Promise<Void> promise){
        String path = request.path();
        try(InputStream inputStream = Application.class.getClassLoader().getResourceAsStream(path.substring(1));
            ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            if(inputStream == null){
                request.response().setStatusCode(404).end();
                return;
            }

            int nRead;
            byte[] data = new byte[4 * 0x400];

            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            byte[] bytes = buffer.toByteArray();
            HttpServerResponse response = request.response();
            if(path.endsWith(".png")){
                response.putHeader("content-type", "image/png");
            }else if(path.endsWith(".jpg")){
                response.putHeader("content-type", "image/jpg");
            }else if(path.endsWith(".gif")){
                response.putHeader("content-type", "image/gif");
            }else if(path.endsWith(".ico")){
                response.putHeader("content-type", "image/x-icon");
            }
            response.putHeader("cache-control", "max-age=315360000");
            response.setStatusCode(200).end(Buffer.buffer(bytes));
        } catch (IOException e) {
            promise.fail(e);
        }
    }

}
